from __future__ import absolute_import, division, print_function

import tensorflow as tf
from  tensorflow import  keras

from  tensorflow.keras import  layers


inputs = keras.layers.Input(shape=(784,),name='img')
h1 = layers.Dense(32,activation=keras.activations.relu)(inputs)

h2 = layers.Dense(32,activation=keras.activations.relu)(h1)

outputs = layers.Dense(10,activation=keras.activations.softmax)(h2)

model = keras.models.Model(inputs= inputs,outputs= outputs,name='minst_model')# 名字字符串中不能有空格

model.compile(optimizer=keras.optimizers.Adam(0.001),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])


model.summary()

keras.utils.plot_model(model, 'mnist_model.png') # 显示基本的信息
keras.utils.plot_model(model, 'model_info.png', show_shapes=True) # 把每一层的结构信息都显示出来了

#验证和测试

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()


x_train = x_train.reshape(60000,784).astype('float32')/255
x_test = x_test.reshape(10000,784).astype('float32')/255

model.fit(x_train,y_train,batch_size=64,epochs= 6,validation_split=0.2)

test_scores = model.evaluate(x_test, y_test, verbose=0)

print("test loss" ,test_scores[0])
print("test accuracy" ,test_scores[1])

# 保存模型

model.save('./model_save.h5')


del model

load_model = keras.models.load_model('./model_save.h5')

test_scores = load_model.evaluate(x_test, y_test, verbose=0)

print("test loss" ,test_scores[0])
print("test accuracy" ,test_scores[1])

